package com.agileboot.api.customize.config;

import com.agileboot.api.customize.ApiTokenUtils;
import com.agileboot.infrastructure.user.AuthenticationUtils;
import com.agileboot.infrastructure.user.app.AppLoginUser;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * token过滤器 验证token有效性
 * 继承OncePerRequestFilter类的话  可以确保只执行filter一次， 避免执行多次
 * @author valarchie
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class ApiAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private ApiTokenUtils apiJwtUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 查询用户信息
        AppLoginUser appUserInfo = apiJwtUtils.getLoginUser(request);

        if (appUserInfo != null && AuthenticationUtils.getAuthentication() == null) {
            apiJwtUtils.refreshToken(appUserInfo);
            UsernamePasswordAuthenticationToken userInfo = new UsernamePasswordAuthenticationToken(appUserInfo, null, appUserInfo.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(userInfo);
        }

        filterChain.doFilter(request, response);
    }
}
